package okhttp.itydl.com.download;

import java.io.IOException;

import okhttp.itydl.com.download.factory.ThreadPoolFactory;
import okhttp.itydl.com.download.file.HttpManager;
import okhttp.itydl.com.download.http.DownloadCallback;
import okhttp.itydl.com.download.proxy.ThreadPoolProxy;
import okhttp.itydl.com.download.utils.Logger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 多线程下载调度 上层对下载的管理类
 *
 * @author howard
 */
public class DownloadManager {

    public static DownloadManager sDownloadManager = null;
    private ThreadPoolProxy downloadExectutor;

    /**
     * 自己定义线程池核心线程数量
     */
    private int MAX_THREAD_COUNT = 3;

    private DownloadManager() {
        downloadExectutor = ThreadPoolFactory.getDownloadExectutor(MAX_THREAD_COUNT, 3000);
    }

    public static DownloadManager getInstance() {
        if (sDownloadManager == null) {
            synchronized (DownloadManager.class) {
                if (sDownloadManager == null) {
                    sDownloadManager = new DownloadManager();
                }
            }
        }
        return sDownloadManager;
    }

    /**
     * 开始下载任务
     */
    public void download(final String url, final DownloadCallback callback) {
        HttpManager.getInstance().asyncRequest(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback != null) {
                    callback.fail(HttpManager.NETWORK_CALLBACK_ERROR, "Okhttp请求Failure");
                }
                Logger.debug("yangdaolong", "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful() && callback != null) {
                    callback.fail(HttpManager.NETWORK_ERROR_CODE, "网络出问题了");
                    return;
                }
                final long contentLength = response.body().contentLength();
                if (contentLength == -1) {
                    callback.fail(HttpManager.CONTENT_LENGTH_ERROR_CODE, "content length -1");
                    return;
                }
                progressDownload(url, callback, contentLength);
            }
        });
    }

    /**
     * 处理请求结果
     */
    private void progressDownload(String url, DownloadCallback callback, long contentLength) {
        long start = 0;
        long end = 0;
        long length = contentLength / MAX_THREAD_COUNT;
        for (int i = 0; i < MAX_THREAD_COUNT; i++) {
            start = i * length;
            end = (i + 1) * length - 1;
            if (i == MAX_THREAD_COUNT - 1) {
                end = contentLength - 1;
            }
            // 添加任务到线程池中
            downloadExectutor.executor(new DownloadRunnable(start, end, url, callback));
        }
    }
}
